package com.hycat.mail.common.handler;

import com.hycat.mail.common.exception.MailException;
import com.hycat.mail.common.model.ExceptionEnum;
import com.hycat.mail.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author : lzhycat
 * @date : 2022-07-19 15:31
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R MailGlobalExceptionHandler(MethodArgumentNotValidException e) {
        HashMap<String, String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((item) -> {
            String field = item.getField();
            String msg = item.getDefaultMessage();
            map.put(field, msg);
        });
        return R.error(ExceptionEnum.PARAM_VERIFY_EXCEPTION).put("detail", map);
    }

    /**
     * 处理自定义抛出异常
     */
    @ExceptionHandler(MailException.class)
    public R MailGlobalExceptionHandler(MailException e) {
        log.info("异常信息为 {}", e.getMessage());
        return R.error(e.getCode(), e.getMessage());
    }

}
